<template>
  <div>
    <el-row>
      <el-col :span="8" style="padding: 10px 0 0 10px;">
        <div class="toolbar">
          <div class="inner-toolbar">
            <div class="toolbar-btns">
              <span class="categary">商品类别</span>
              <el-button size="mini" v-if="checkPermission(['category:add'])" type="primary"
                         @click="handleAddCategary">新增</el-button>
            </div>
          </div>
        </div>
        <el-tree :data="categorys" node-key="identifier" :expand-on-click-node="true" :style="{height: categoryHeight}">
        <span class="custom-tree-node" slot-scope="{node, data}" @click="handleSeachShop(data)">
          <span>{{ data.name }}</span>
          <span>
          <el-button type="text" size="mini" :disabled="node.level === 3" icon="el-icon-plus"
                     :title="node.level === 3 ? '类别最多添加三级' : '增加'" v-if="checkPermission(['category:add'])"
                     @click.stop="handleAddCategary(data)"></el-button>
          <el-button type="text" style="color: #F56C6C" size="mini" icon="el-icon-minus" v-if="checkPermission(['category:del'])"
                     @click.stop="handleDeleteCategory(data)"></el-button>
          <el-button type="text" size="mini" icon="el-icon-edit" v-if="checkPermission(['category:edit'])"
                     @click.stop="handleEditCategary(data)"></el-button>
          <el-button type="text" size="mini" icon="el-icon-setting" v-if="checkPermission(['category:spec'])"
                     @click.stop="handleEditSpecs(data)">规格</el-button>
          <el-button type="text" size="mini" icon="el-icon-setting" v-if="checkPermission(['category:params'])"
                     @click.stop="handleEditParams(data)">参数</el-button>
        </span>
        </span>
          </el-tree>
      </el-col>
      <el-col :span="16">
        <en-table-layout :tableData="tableData.data" :loading="loading" style="padding: 10px 10px 0 10px;">
          <div slot="toolbar" class="inner-toolbar">
            <div class="toolbar-btns">
              <el-button size="mini" v-if="checkPermission(['goods:add'])" type="primary" @click="handleAddGoods">新增</el-button>
            </div>
            <div class="toolbar-search" style="display:flex;align-items: center;">
              <en-table-search @search="searchEvent" placeholder="请输入关键字搜索" />
              <el-button @click="refresh" icon="el-icon-refresh" type="info" plain></el-button>
            </div>
          </div>

          <template slot="table-columns">
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="sn" label="商品编号" />
            <el-table-column prop="category_name" label="商品类别" />
            <el-table-column prop="brand_name" label="品牌" />
            <el-table-column prop="price" label="价格" :formatter="MixinFormatPrice"/>
            <el-table-column prop="label_names" label="商品标签"/>
            <el-table-column label="状态" key="market_enable">
              <template slot-scope="scope">
                <span>{{ scope.row.market_enable ? '上架' : '下架' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200px">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" v-if="checkPermission(['goods:edit'])"
                           @click="handleEditGoods(scope.row)">编辑</el-button>
                <el-button size="mini" v-if="checkPermission(['goods:del'])" type="danger"
                           @click="handleDeleteGoods(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </template>

          <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
                         @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
                         :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
          </el-pagination>
        </en-table-layout>
      </el-col>
    </el-row>
    <!--编辑分类dialog-->
    <el-dialog :title="categoryForm.name ? '编辑类别' : '添加类别'" :visible.sync="dialogCategoryVisible" width="500px"
               :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="categoryForm" ref="categoryForm" label-width="100px">
        <el-form-item label="上级类别名称" prop="parent_id">
          <el-cascader v-model="categoryForm.parent_id" :options="categorys" :props="{
              label: 'name',
              value: 'category_id',
              emitPath: false,
              checkStrictly: true
            }" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="商品类别名称" prop="category_name">
          <el-input v-model="categoryForm.category_name" :maxlength="6"></el-input>
        </el-form-item>
        <el-form-item label="商品类别编号" prop="custom_sn">
          <el-input v-model="categoryForm.custom_sn"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogCategoryVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCategoryForm('categoryForm')">确 定</el-button>
        </span>
    </el-dialog>
    <!--编辑关联规格dialog-->
    <el-dialog
      title="关联规格"
      width="500px"
      :visible.sync="dialogSpecsVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="specsForm" ref="specsForm">
        <el-form-item label="选择规格">
          <el-select v-model="specsForm.selectedSpecsList" placeholder="请选择关联规格" multiple filterable style="width: 350px">
            <el-option
              v-for="item in specsForm.specsList"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSpecsVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSpecsForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Goods from '@/api/goods'
import * as API_Category from '@/api/category'

export default {
  name: 'productFile',
  data() {
    return {
      categorys: [],
      categoryForm: {},
      dialogCategoryVisible: false,
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10,
        category_id: ''
      },
      // 列表数据
      tableData: '',
      dialogSpecsVisible: false,
      // 编辑关联规格 表单
      specsForm: {
        category_id: null,
        selectedSpecsList: [],
        specsList: []
      },
      // 左侧商品分类高度，和table保持一致
      categoryHeight: `${document.body.clientHeight - 219}px`
    }
  },
  mounted() {
    this.GET_ProductList()
    this.GET_Category()
  },
  methods: {
    handleEditGoods(row) {
      this.$router.push({
        name: 'goodsEditForm',
        params: { id: row.id }
      })
    },
    /** 编辑关联规格 */
    handleEditSpecs(cat) {
      API_Category.getSpecsByCategoryId(cat.category_id).then(response => {
        this.specsForm = {
          ...this.specsForm,
          category_id: cat.category_id,
          specsList: response,
          selectedSpecsList: response.filter(item => item.selected).map(item => item.id)
        }
        this.dialogSpecsVisible = true
      })
    },
    /** 编辑分类参数 */
    handleEditParams(cat) {
      this.$router.push({ name: 'categoryParams', params: { id: cat.category_id }})
    },
    /** 编辑关联规格 表单提交 */
    submitSpecsForm() {
      API_Category.updateCategorySpecs(this.specsForm.category_id, this.specsForm.selectedSpecsList).then(response => {
        this.dialogSpecsVisible = false
        this.$message.success('保存成功！')
      })
    },
    refresh() {
      this.params.page_no = 1
      this.params.category_id = ''
      this.GET_ProductList()
    },
    handleSeachShop(data) {
      this.params.page_no = 1
      this.params.category_id = data.category_id
      this.GET_ProductList()
    },
    submitCategoryForm(formName) {
      const { category_id } = this.categoryForm
      if (!category_id) {
        API_Category.addCategory(this.categoryForm).then(() => {
          this.dialogCategoryVisible = false
          this.$message.success('保存成功！')
          this.$refs[formName].resetFields()
          this.GET_Category()
        })
      } else {
        API_Category.editCategory(category_id, this.categoryForm).then(response => {
          this.$message.success('保存成功！')
          this.dialogCategoryVisible = false
          this.$refs[formName].resetFields()
          this.GET_Category()
        })
      }
    },
    handleDeleteCategory(category) {
      this.$confirm('确定要删除这个分类吗？', '提示', { type: 'warning' }).then(() => {
        API_Category.deleteCategory(category.category_id).then(() => {
          this.$message.success('删除成功！')
          this.GET_Category()
        })
      }).catch(() => { })
    },
    /** 添加类别 */
    handleAddCategary(category) {
      this.categoryForm = {
        parent_id: category ? category.category_id : 0
      }
      this.dialogCategoryVisible = true
    },
    /** 编辑类别  */
    handleEditCategary(category) {
      this.categoryForm = {
        parent_id: category.parent_id,
        category_id: category.category_id,
        category_name: category.name,
        custom_sn: category.custom_sn
      }
      this.dialogCategoryVisible = true
    },
    /** 获取类别 */
    GET_Category() {
      API_Category.getCategoryAllChildren(0).then(response => {
        this.categorys = response
      })
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_ProductList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_ProductList()
    },

    /** 添加商品档案 */
    handleAddGoods() {
      this.$router.push({
        name: 'goodsAddForm'
      })
    },

    /** 删除商品档案 */
    handleDeleteGoods(row) {
      this.$confirm('确定要删除这个商品档案吗？', '提示', { type: 'warning' }).then(() => {
        API_Goods.deleteGoods(row.id).then(() => {
          this.$message.success('删除成功！')
          this.GET_ProductList()
        })
      }).catch((error) => {
        console.log(error)
      })
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keyword: data
      }
      this.params.page_no = 1
      this.GET_ProductList()
    },

    /** 获取商品档案列表 */
    GET_ProductList() {
      this.loading = true
      API_Goods.getGoodsList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.toolbar {
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: 45px;
  border-bottom: 1px solid #e6ebf5;
  background-color: #fff;
}

.inner-toolbar {
  padding: 0 20px;

  .categary {
    padding-right: 10px;
    font-size: 14px;
  }
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: 500px;
}
</style>
